import React, { Component } from "react";
import PubSub from "pubsub-js"
import axios from "axios";

export default class Search extends Component {

  //搜索
  handleSearch = () => {
    const {keywordElement:{value:keyword}} = this;
    //发布消息 兄弟组件通信
    PubSub.publish('search', {isFirst: false, isLoading: true}) 
    let url = "/api/search/users"
    axios.get(`${url}?q=${keyword}`).then(res => {
      if(res.status === 200) {
        let data = res.data.items;
        PubSub.publish('search', { isLoading: false, users: data})
      }
    }).catch(err => {
      PubSub.publish('search', { isLoading: false, users: [], err: err.message})
    })
  }

  render() {
    return (
      <section className="jumbotron">
        <h3 className="jumbotron-heading">搜索github 用户</h3>
        <div>
          <input ref={(c) => this.keywordElement = c} type="text" placeholder="请输入关键词" />
          <button onClick={this.handleSearch}>搜索</button>
        </div>
      </section>
    );
  }
}
